<?php


namespace app\api\job;


use app\admin\model\chase\Order as OrderModel;
use app\api\model\Orders;
use app\api\model\Refunds;
use think\Db;
use think\queue\Job;
use Yansongda\Pay\Pay;

class CancelOrder
{
    /**
     * fire方法是消息队列默认调用的方法
     * @param Job            $job      当前的任务对象
     * @param array|mixed    $data     发布任务时自定义的数据
     */
    public function fire(Job $job,$data)
    {
        // 有些消息在到达消费者时,可能已经不再需要执行了
        $isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
        if(!$isJobStillNeedToBeDone){
            $job->delete();
            return;
        }

        $isJobDone = $this->doHelloJob($data);

        if ($isJobDone) {
            // 如果任务执行成功， 记得删除任务
            $job->delete();
            print("<info>Hello Job has been done and deleted"."</info>\n");
        }else{
            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
                print("<warn>Hello Job has been retried more than 3 times!"."</warn>\n");

                $job->delete();

                // 也可以重新发布这个任务
                //print("<info>Hello Job will be availabe again after 2s."."</info>\n");
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }

    /**
     * 有些消息在到达消费者时,可能已经不再需要执行了
     * @param array|mixed    $data     发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    private function checkDatabaseToSeeIfJobNeedToBeDone($data){
        $refund = Refunds::find($data['refund_id']);
        if (!$refund || $refund->status != 1) {
            return false;
        }
        return true;
    }

    /**
     * 根据消息中的数据进行实际的业务处理...
     */
    private function doHelloJob($data)
    {
        $refund = Refunds::find($data['refund_id']);
        $order = Orders::where('order_no', $data['order_no']);
        if (!$order) {
            return true;
        }
        Db::startTrans();
        try {
            $pay = Pay::wechat(config('wechat'));
            $res = $pay->refund([
                'out_trade_no' => $order->order_no,
                'out_refund_no' => 'R' . date('YmdHis').mt_rand(100, 999),
                'total_fee' => $order->total_amount * 100,
                'refund_fee' => $order->total_amount * 100,
            ]);
            if ($res['return_code'] === 'SUCCESS' && $res['result_code'] === 'SUCCESS') {
                $refund->status = 3;
                $refund->total_fee = $res['total_fee'] / 100;
                $refund->transaction_id = $res['transaction_id'];
                $refund->save();
                $order->status = 5;
                $order->save();
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        return isset($e) ? false : true;

    }
}